$(function () {
    $("div.form").height($(parent.window).height() - 120); //将弹出层表单自适应高度
    $("a.moveBtn").hover(function () {//动态按钮
        if (!$(this).find("img").is(":animated")) {
            $(this).find("img")
			.animate({ top: "-10px" }, 200).animate({ top: "-4px" }, 200)
			.animate({ top: "-7px" }, 100).animate({ top: "-4px" }, 100)
			.animate({ top: "-6px" }, 100).animate({ top: "-4px" }, 100);
        }
    });

    $(".form-control").blur(function () {
        $(this).val($(this).val());
        if (typeof validate === 'function') {
            validate();
        }
    });
    $(":checkbox.checkboxCtrl", $("body")).checkboxCtrl($("body"));
    ////////////////---===分页--===///////////////////////////////////
    initPage();
    ////////////////---===分页--===///////////////////////////////////
});
function initPage()
{
    if ($("#pager").length > 0) {
        $("#pager").zPager({
            current: parseInt($("#hidCurrentPageIndex").val()),
            totalData: parseInt($("#hidTotalCount").val()),
            pageData: parseInt($("#hidPageSize").val())
        });
        $("#pager a").click(function () {
            if ($(this).attr("disabled") == "disabled") { return; }
            var currentPageIndex = $(this).attr("page-id");
            $("#hidCurrentPageIndex").val(currentPageIndex)
            if (typeof (doSumbitCallBack) == 'function') {
                doSumbitCallBack('ChangePage'); //回调函数,在aspx页面时实现其方法
            }
            else {
                Dialog.error("没有实现回调方法：doSumbitCallBack");
            }
        })
        $("#ddlPageSize").val($("#hidPageSize").val());
        $("#ddlPageSize").change(function () {
            $("#hidPageSize").val($(this).val());
            $("#hidCurrentPageIndex").val("1")
            if (typeof (doSumbitCallBack) == 'function') {
                doSumbitCallBack(); //回调函数,在aspx页面时实现其方法
            }
            else {
                Dialog.error("没有实现回调方法：doSumbitCallBack");
            }
        });
        //$("#txtGoPage").val($("#hidCurrentPageIndex").val());
        $("#btnGoPage").click(function () {
            var intGoPage = parseInt($("#txtGoPage").val());
            var intTotalPage = parseInt($("#pager").children(":last-child").attr("page-id"));
            if (intGoPage > 0 && intGoPage <= intTotalPage) {
                $("#hidCurrentPageIndex").val(intGoPage);
                if (typeof (doSumbitCallBack) == 'function') {
                    doSumbitCallBack('ChangePage'); //回调函数,在aspx页面时实现其方法
                }
                else {
                    Dialog.error("没有实现回调方法：doSumbitCallBack");
                }
            }
            else {
                AlertWarning("超出页面码范围");
            }
        });
    }
}
//compare date 
function compareDate(endTime, beginTime) {
    return ((new Date(endTime.replace(/-/g, "\/"))) > (new Date(beginTime.replace(/-/g, "\/"))));
}
//Checkbox选中
(function ($) {
    $.fn.extend({
        checkboxCtrl: function (parent) {
            return this.each(function () {
                var $trigger = $(this);
                $trigger.click(function () {
                    var group = $trigger.attr("group");
                    if ($trigger.is(":checkbox")) {
                        var type = $trigger.is(":checked") ? "all" : "none";
                        if (group) $.checkbox.select(group, type, parent);
                    } else {
                        if (group) $.checkbox.select(group, $trigger.attr("selectType") || "all", parent);
                    }

                });
            });
        }
    });

    $.checkbox = {
        selectAll: function (_name, _parent) {
            this.select(_name, "all", _parent);
        },
        unSelectAll: function (_name, _parent) {
            this.select(_name, "none", _parent);
        },
        selectInvert: function (_name, _parent) {
            this.select(_name, "invert", _parent);
        },
        select: function (_name, _type, _parent) {
            $parent = $(_parent || document);
            $checkboxLi = $parent.find(":checkbox[name='" + _name + "']");
            switch (_type) {
                case "invert":
                    $checkboxLi.each(function () {
                        $checkbox = $(this);
                        $checkbox.attr('checked', !$checkbox.is(":checked"));
                    });
                    break;
                case "none":
                    $checkboxLi.attr('checked', false);
                    break;
                default:
                    $checkboxLi.attr('checked', true);
                    break;
            }
        }
    };
})(jQuery);

//提交表单通用方法
function validateCallback(form, callback) {
    showLoading();
    var isValid = true;
    if (typeof validate === 'function') {
        isValid=validate();
    }
    if(isValid)
    {
        var $form = $(form);
        $.ajax({
            type: form.method || 'POST',
            url: $form.attr("action"),
            data: $form.serializeArray(),
            dataType: "json",
            cache: false,
            success: callback,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    }
    hideLoading();
    return false;
}

function ajaxTodo(url, callback) {
    var $callback = callback;
    if (!$.isFunction($callback)) $callback = eval('(' + callback + ')');
    $.ajax({
        type: 'POST',
        url: url,
        dataType: "json",
        cache: false,
        success: $callback,
        error: function () { }
    });
}

////处理键盘事件 禁止后退键（Backspace）密码或单行、多行文本框除外        
//function forbidBackSpace(e) {            var ev = e || window.event; //获取event对象             
//    var obj = ev.target || ev.srcElement; //获取事件源             
//    var t = obj.type || obj.getAttribute('type'); //获取事件源类型             //获取作为判断条件的事件类型             
//    var vReadOnly = obj.readOnly;            
//    var vDisabled = obj.disabled;            //处理undefined值情况             
//    vReadOnly = (vReadOnly == undefined) ? false : vReadOnly;            
//    vDisabled = (vDisabled == undefined) ? true : vDisabled;            //当敲Backspace键时，事件源类型为密码或单行、多行文本的，             //并且readOnly属性为true或disabled属性为true的，则退格键失效             
//    var flag1 = ev.keyCode == 8 && (t == "password" || t == "text" || t == "textarea") && (vReadOnly == true || vDisabled == true);            //当敲Backspace键时，事件源类型非密码或单行、多行文本的，则退格键失效             
//    var flag2 = ev.keyCode == 8 && t != "password" && t != "text" && t != "textarea";            //判断             
//    if (flag2 || flag1) return false;
//}        //禁止后退键 作用于Firefox、Opera        
//document.onkeypress = forbidBackSpace;        //禁止后退键  作用于IE、Chrome        
//document.onkeydown = forbidBackSpace;


//取静态页参数////////////////
function GetQueryString(key) {
    var result = location.search.match(new RegExp("[\?\&]" + key + "=([^\&]+)", "i"));
    if (result == null || result.length < 1) {
        return "";
    }
    return result[1];
}
///url添加时间戳 
function addURLTimeStamp(url) {
    var time = new Date();
    var timstamp = time.toString() + time.getMilliseconds().toString();
    if (url.indexOf("?") >= 0) {
        url = url + "&t=" + timstamp;
    } else {
        url = url + "?t=" + timstamp;
    };
    return url;
};
//加载效果
function showLoading()
{
    $("body").append("<div class='waiting'></div>");
    if (GetQueryString("t") != "" && GetQueryString("t") != null && GetQueryString("t") != undefined)//webQQ模式打开时，特殊处理
    {
        $("div.waiting").css("top", (document.documentElement.clientHeight - $("div.waiting").height()) / 2 + $(document).scrollTop() + 35);
        if ($("div.waiting").css("top")=="3px")
        {
            $("div.waiting").css("top", "300px");
        }
    }
    else
    {
        $("div.waiting").css("top", (document.documentElement.clientHeight - $("div.waiting").height()) / 2 + $(document).scrollTop() +35);
    }
}
//加载完成，隐藏效果
function hideLoading()
{
    $("div.waiting").css("opacity","0").fadeOut();
}
//打开用户信息窗体
function doOpenUserInfo(isOpenByZcDialog, tabIndex) {
    //兼容苹果浏览器，如果有做url重定向的页面打开Dialog（如user->sys/userlist.aspx），需要做兼容Safari处理，否则不需要处理
    var prefixURL = "../../";
    var titleName;
    if (tabIndex == "0") {
        titleName = "我的资料";
    }
    if (tabIndex == "1")
    {
        titleName = "上传头像";
    }
    if (tabIndex == "2")
    {
        titleName = "修改密码";

        if (isSafari()) {
            prefixURL = "";
        }
    }
    var url = prefixURL + "Cloud/Sys/UserInfo.aspx";
    if (tabIndex != undefined || tabIndex != null) {
        url = url + "?tabIndex=" + tabIndex;
    }
    url = addURLTimeStamp(url);
    if (isOpenByZcDialog == "Y") {//网页风格使用ZcDialog打开
        var diag = new Dialog();
        diag.Width = 720;
        diag.Height = 430;
        diag.Title = titleName;
        diag.URL = url;
        diag.show();
    }
    else {
        var windowOption = {
            title: titleName,
            url: url,
            winMax: false,
            height: "530px",
            y: ($(window).height() - 530) / 2
        };
        bmcp_window.open(windowOption);
    }
}

///根据字段名称获取Js用户数据
//function UserProfile(key) {
//    var obj = $("#" + key, parent.document);
//    if (obj == undefined || obj == null || obj.val() == undefined) {
//        obj = $("#" + key);
//    }
//    return obj.val();
//}
////锁定系统
//function doLockSystem() {
//    var diag = new Dialog();
//    diag.Width = 430;
//    diag.Height = 220;
//    diag.Title = "系统已被锁定";
//    diag.ShowCloseButton = false;
//    diag.URL = addURLTimeStamp("../../Portal/Win/LockSystem.html?loginID=" + UserProfile("LoginID") + "&userName=" + escape(UserProfile("UserName")));
//    diag.show();
//}
//validate free user accessrights
function validateFreeUser(type,status,trialCount)
{
    if (isSupportLocalStorage()) {
        if (status.toLowerCase() == "free") {
            var count = localStorage[type];
            if (count != undefined&&!isNaN(count)) {
                count = parseInt(count);
                if (count >= parseInt(trialCount)) {
                    Dialog.alert('&nbsp;&nbsp;&nbsp;升级提示：此功能试用结束，只对付费版本开放，<a href="../../buy" target="_blank" style="color:rgb(255, 106, 0)">点击升级!</a>');
                    return false;
                }
                count++;
                localStorage[type] = count;
            }
            else {
                localStorage[type] = 0;
            }
        }
        else {
            localStorage[type] = 0;
        }
    }
    return true;
}
function doExit()//安全退出
{
    Dialog.confirm('确认退出系统吗?', function () { window.location = '../../Cloud/Main/Exit.aspx' });
}

///返回选择的项编号
function selectCheckBoxID(chkName) {
    var number = 0;
    var primaryID = "";
    $("input:checkbox[name=" + chkName + "]:checked").each(function () {
        number++;
        primaryID += $(this).val() + ",";
    });

    primaryID = primaryID.substring(0, primaryID.length - 1)
    return primaryID;
}

function selectAllCheckBoxID(chkName) {
    var number = 0;
    var primaryID = "";
    $("input:checkbox[name=" + chkName + "]").each(function () {
        number++;
        primaryID += $(this).val() + ",";
    });

    primaryID = primaryID.substring(0, primaryID.length - 1)
    return primaryID;
}

//验证是否为整数
function isDigits(value)
{
    if (/^\d+$/.test(value)) {
        return true;
    }
    else {
        false;
    }
}
//判断是否为邮箱
function isEmail(value) {
    if (/^[a-zA-Z0-9_-]+(\.([a-zA-Z0-9_-])+)*@[a-zA-Z0-9_-]+[.][a-zA-Z0-9_-]+([.][a-zA-Z0-9_-]+)*$/.test(value)) {
        return true;
    }
    else {
        false;
    }    
}

//判断是否为数字
function isNumber(value) {
    if (/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value)) {
        return true;
    }
    else {
        false;
    }
}
//判断是否为手机号码
function isTelephone(value) {
    var reg = /^(0|86|17951)?(13[0-9]|14[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])[0-9]{8}$/;
    if (reg.test(value)) {
        return true;
    }
    else {
        return false;
    }
}

function isSetupFlash() {
    var hasFlash = false;　　　　 //是否安装了flash  
    var flashVersion = 0;　　 //flash版本  
    if (document.all) {
        var swf = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
        if (swf) {
            hasFlash = true;
        }
    } else {
        if (navigator.plugins && navigator.plugins.length > 0) {
            var swf = navigator.plugins["Shockwave Flash"];
            if (swf) {
                hasFlash = true;
            }
        }
    }
    return hasFlash;
}
//判断考生是手机还是PC
function IsPC() {
    var userAgentInfo = navigator.userAgent;
    var Agents = ["Android", "iPhone",
                "SymbianOS", "Windows Phone",
                "iPad", "iPod"];
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}
function isSupportWeui() {
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    var isIE = (window.ActiveXObject != undefined && userAgent.indexOf("MSIE") != -1) || !!window.ActiveXObject || "ActiveXObject" in window;
    if (isIE) {
        return false;
    }
    else {
        return true;
    }
}
//检查是否支持本地存储
function isSupportLocalStorage() {
    if (window.Storage && window.localStorage && window.localStorage instanceof Storage) {
        return true;
    }
    else {
        return false;
    }
}
///判断是否是苹果浏览器
function isSafari()
{
    return navigator.userAgent.indexOf("Safari") > -1 && navigator.userAgent.indexOf("Chrome") == -1;
}

//success alert
function AlertSuccess(msg, second)
{
    var randomID = "success" + Math.floor(Math.random() * 100000);
    var top = 60* $("div.alert-dismissable").not(":hidden").length+20;
    
    var content = '<div id="' + randomID + '" class="alert alert-success alert-dismissable" style="position:fixed;font-size:14px;top:'+top+'px;right:10px;z-index:10000000;min-width:350px;border-radius:0px;border-left:5px solid #3c763d;">';
    content += '<button type="button" onclick="$(\'#'+randomID+'\').remove();" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
    content += '<span style="font-size:16px;font-weight:bold">✔</span> <span>' + msg + '</span></div>';
    $(content).appendTo($("body"));
    if (second == undefined || second == "") second = 3000;
    setTimeout(function () { $("#"+randomID).fadeOut(1000); }, second);
}
//info alert
function AlertInfo(msg, second) {
    var randomID = "info" + Math.floor(Math.random() * 100000);
    var top = 60 * $("div.alert-dismissable").not(":hidden").length + 20;

    var content = '<div id="' + randomID + '" class="alert alert-info alert-dismissable" style="position:fixed;font-size:14px;top:' + top + 'px;right:10px;z-index:10000000;width:350px;border-radius:0px;border-left:5px solid #31708f;">';
    content += '<button type="button" onclick="$(\'#' + randomID + '\').remove();" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
    content += '<span style="font-size:16px;font-weight:bold">☉</span>  <span>' + msg + '</span></div>';
    $(content).appendTo($("body"));
    if (second == undefined || second == "") second = 3000;
    setTimeout(function () { $("#" + randomID).fadeOut(1000); }, second);
}
//warning alert
function AlertWarning(msg, second) {
    var randomID = "warning" + Math.floor(Math.random() * 100000);
    var top = 60 * $("div.alert-dismissable").not(":hidden").length + 20;

    var content = '<div id="' + randomID + '" class="alert alert-warning alert-dismissable" style="position:fixed;font-size:14px;top:' + top + 'px;right:10px;z-index:10000000;width:350px;border-radius:0px;border-left:5px solid #8a6d3b;">';
    content += '<button type="button" onclick="$(\'#' + randomID + '\').remove();" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
    content += '<span style="font-size:16px;font-weight:bold">ⓘ</span>  <span>' + msg + '</span></div>';
    $(content).appendTo($("body"));
    if (second == undefined || second == "") second = 3000;
    setTimeout(function () { $("#" + randomID).fadeOut(1000); }, second);
}
//error alert
function AlertError(msg, second) {
    var randomID = "error" + Math.floor(Math.random() * 100000);
    var top = 60 * $("div.alert-dismissable").not(":hidden").length + 20;

    var content = '<div id="' + randomID + '" class="alert alert-danger alert-dismissable" style="position:fixed;font-size:14px;top:' + top + 'px;right:10px;z-index:10000000;width:350px;border-radius:0px;border-left:5px solid #a94442;">';
    content += '<button type="button" onclick="$(\'#' + randomID + '\').remove();" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
    content += '<span style="font-size:16px;font-weight:bold">ㄨ</span>  <span>' + msg + '</span></div>';
    $(content).appendTo($("body"));
    if (second == undefined || second == "") second = 3000;
    setTimeout(function () { $("#" + randomID).fadeOut(1000); }, second);
}
//判断是否为IE浏览器，不包括edge
function isIEBroswer() {
    if (!!window.ActiveXObject || "ActiveXObject" in window)
        return true;
    else
        return false;
}